<script setup lang="ts">
import { PropType, reactive, ref, watch } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  actionType: {
    type: String as PropType<'add' | 'edit'>,
    default: 'add'
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'id',
    label: 'ID',
    component: 'Input',
    show: props.actionType === 'edit', // 仅编辑模式下显示
    colProps: {
      span: 12
    },
    componentProps: {
      disabled: true, // 设为禁用状态
      placeholder: '系统自动生成'
    }
  },
  {
    field: 'name',
    label: '房间名称',
    component: 'Input',
    colProps: {
      span: 12
    },
    componentProps: {
      placeholder: '请输入房间名称',
      clearable: true
    }
  },
  {
    field: 'type',
    label: '房间类型',
    component: 'Select',
    colProps: {
      span: 12
    },
    componentProps: {
      placeholder: '请选择房间类型',
      clearable: true,
      options: [
        { label: '医院', value: 'hospital' },
        { label: '住宅', value: 'residential' }
      ]
    },
    value: 'hospital'
  },
  {
    field: 'location',
    label: '位置',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入房间位置信息',
      clearable: true
    }
  }
])

const rules = reactive({
  name: [required()],
  type: [required()],
  location: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const validate = async () => {
  const elForm = await getElFormExpose()
  return await elForm?.validate().catch(() => false)
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // 确保在编辑模式下保存ID
    setValues({
      id: currentRow.id,
      name: currentRow.name,
      type: currentRow.type,
      location: currentRow.location
    })
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.actionType,
  (actionType) => {
    // 根据动作类型动态更新ID字段的显示状态
    formSchema.find((item) => item.field === 'id')!.show = actionType === 'edit'
  },
  { immediate: true }
)

defineExpose({
  validate,
  getFormData
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" label-width="100px" />
</template>
